package com.example.imagetest;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.InputType;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.imagetest.util.UploadUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FileChooserActivity extends AppCompatActivity {

    private static final String TAG = "FileChooserActivity";
    private static final int PERMISSION_REQUEST_CODE = 1;
    private static final String MINIO_UPLOAD_URL = "http://192.168.1.228:8089/product/file/upload";
    private File downloadedFile;

    // 用于启动intent跳转的启动器
    private final ActivityResultLauncher<Intent> galleryLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                // 检查文件选择操作是否成功并且返回的数据是否不为空
                if (result.getResultCode() == Activity.RESULT_OK && result.getData() != null) {
                    // 从返回的数据中获取选中文件的URI
                    Uri fileUri = result.getData().getData();
                    // 将文件的URI转换为实际的文件路径
                     String filePath = getRealPathFromURI(fileUri);
                    Log.d(TAG, "文件路径是" + filePath);
                    if (filePath != null) {
                        File file = new File(filePath);
                        // 调用uploadFile方法将文件上传到服务器
                        uploadFile(file);
                    } else {
                        Toast.makeText(this, "无法获取文件路径", Toast.LENGTH_SHORT).show();
                    }
                }
            }
    );

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_chooser);

        Button btnSelectFromGallery = findViewById(R.id.btn_select_from_gallery);
        Button btnUploadUrl = findViewById(R.id.btn_upload_url);
        Button btnDownloadUrl = findViewById(R.id.btn_download_url);

        // 为三种选择按钮绑定单击事件
        btnSelectFromGallery.setOnClickListener(view -> openGallery());
        btnUploadUrl.setOnClickListener(view -> showUrlUploadInputDialog());
        btnDownloadUrl.setOnClickListener(view -> showUrlDownloadInputDialog());

        // 检查是否有写入外部存储的权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 如果没有，则请求该权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_CODE);
        }
    }

    /**
     * 处理权限请求结果
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            // 如果权限被拒绝，则输出错误日志信息。
            if (grantResults.length <= 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                Log.e(TAG, "Permission denied");
            }
        }
    }

    /**
     * 打开图库
     */
    private void openGallery() {
        // 创建一个用于获取内容的Intent
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        // 设置Intent的类型为任意文件类型
        intent.setType("*/*");
        // 定义一个字符串数组，包含图片和视频的MIME类型
        String[] mimeTypes = {"image/*", "video/*"};
        // 将MIME类型数组作为额外参数添加到Intent中，这样选择器会显示图片和视频文件
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        // 使用之前定义的ActivityResultLauncher启动选择器
        galleryLauncher.launch(intent);
    }

    /**
     * 弹出上传输入框
     */
    private void showUrlUploadInputDialog() {
        // AlertDialog.Builder用于构建和显示对话框，其中参数context是指当前Activity的上下文
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("输入 URL ");

        final EditText input = new EditText(this);
        // 指定输入类型
        input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
        builder.setView(input);

        builder.setPositiveButton("上传", (dialog, which) -> {
            String url = input.getText().toString();
            if (!url.isEmpty()) {
                uploadUrl(url);
            } else {
                Toast.makeText(this, "URL 不能为空", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

        builder.show();
    }

    /**
     * 弹出下载保存输入框
     */
    private void showUrlDownloadInputDialog() {
        // AlertDialog.Builder用于构建和显示对话框，其中参数context是指当前Activity的上下文
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("输入 URL");

        final EditText input = new EditText(this);
        // 指定输入类型
        input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
        builder.setView(input);

        builder.setPositiveButton("下载", (dialog, which) -> {
            String url = input.getText().toString();
            if (!url.isEmpty()) {
                downloadFile(url);
            } else {
                Toast.makeText(this, "URL 不能为空", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

        builder.show();
    }

    /**
     * 根据url下载文件
     * @param url
     */
    private void downloadFile(String url) {
        Log.d(TAG, "调用文件下载方法");
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.e(TAG, "下载文件失败: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    InputStream inputStream = null;
                    OutputStream outputStream = null;
                    try {
                        // 在设备的外部文件目录中创建一个临时文件，用于存储下载的文件
                        String suffix = url.substring(url.lastIndexOf("."));
                        Log.e(TAG, "文件后缀名为" + suffix);

                        downloadedFile = File.createTempFile("downloaded_file", suffix, getExternalFilesDir(Environment.DIRECTORY_PICTURES));

                        inputStream = response.body().byteStream();
                        outputStream = new FileOutputStream(downloadedFile);

                        byte[] buffer = new byte[2048];
                        int bytesRead;
                        // 将输入流写入文件输出流
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }

                        // 保存到安卓设备的图库
                        saveFileToGallery(Uri.fromFile(downloadedFile).toString());

                        // 下载、保存成功后，自动上传文件
                        // uploadFile(downloadedFile);

                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e(TAG, "文件保存失败: " + e.getMessage());
                    } finally {
                        // 关闭输入流和输出流
                        if (inputStream != null) inputStream.close();
                        if (outputStream != null) outputStream.close();
                    }
                }
            }
        });
    }

    /**
     * 将文件保存到图库
     * @param filePath
     */
    private void saveFileToGallery(String filePath) {
        Log.e(TAG,"调用文件保存方法");
        Log.e(TAG, "文件路径为" + filePath);
        if (filePath.startsWith("file:///"))
            filePath = Uri.parse(filePath).getPath();

        File file = new File(filePath);
        if (!file.exists()) {
            Log.e(TAG, "文件不存在，无法保存到图库: " + filePath);
            return;
        }

        try {
            String mimeType = getMimeType(filePath);
            Uri externalUri;
            if (mimeType.startsWith("image/")) {
                externalUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                Log.d(TAG, "文件类型为文件");
            } else if (mimeType.startsWith("video/")) {
                externalUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                Log.d(TAG, "文件类型为视频");
            } else {
                Log.e(TAG, "不支持的文件类型: " + mimeType);
                return;
            }

            // 插入媒体库，在 Andriod 应用中的"图库"上显示
            ContentValues values = new ContentValues();
            // ContentValues 用于存储要插入到媒体库中的文件的相关信息
            values.put(MediaStore.MediaColumns.DISPLAY_NAME, file.getName());
            values.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
            // 对于不同的文件类型，存储到图库中对应的目录
            if (mimeType.startsWith("image/"))
                values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
            else if (mimeType.startsWith("video/"))
                values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_MOVIES);
            Log.d(TAG, "ContentValues的值为" + values.toString());

            Uri uri = getContentResolver().insert(externalUri, values);
            if (uri != null) {
                OutputStream outStream = getContentResolver().openOutputStream(uri);
                FileInputStream inStream = new FileInputStream(file);
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
                outStream.close();
                inStream.close();

                // 更新系统媒体库，通知系统有新文件添加，以便系统可以更新媒体库并在其他应用中显示新添加的文件
                MediaScannerConnection.scanFile(this, new String[]{filePath}, null, (path, uri1) -> {
                    Log.d(TAG, "文件保存并更新到媒体库成功：" + path);
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "保存文件到图库失败: " + e.getMessage());
        }
    }

    /**
     * 上传文件到后端服务器
     * @param file
     */
    private void uploadFile(File file) {
        OkHttpClient client = UploadUtils.createOkHttpClient();
        // 动态获取文件的MIME类型
        String mimeType = UploadUtils.getMimeType(file.getAbsolutePath());
        RequestBody fileBody = UploadUtils.createMultipartBody(file, mimeType);

        Request request = new Request.Builder()
                .url(MINIO_UPLOAD_URL)
                .post(fileBody)
                .build();

        UploadUtils.logRequestDetails(MINIO_UPLOAD_URL, file);

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.e(TAG, "上传文件失败: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                UploadUtils.handleResponse(response);
            }
        });
    }

    /**
     * 上传url到后端服务器
     * @param fileUrl
     */
    private void uploadUrl(String fileUrl) {
        OkHttpClient client = UploadUtils.createOkHttpClient();

        RequestBody formBody = new FormBody.Builder()
                .add("obj", fileUrl)
                .build();

        Request request = new Request.Builder()
                .url(MINIO_UPLOAD_URL)
                .post(formBody)
                .build();

        Log.d(TAG, "请求服务的url为:" + MINIO_UPLOAD_URL);
        Log.d(TAG, "上传的文件路径: " + fileUrl);

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.e(TAG, "上传文件URL失败: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                UploadUtils.handleResponse(response);
            }
        });
    }

    /**
     * 根据URI获取文件的绝对路径
     * @param contentUri
     * @return
     */
    private String getRealPathFromURI(Uri contentUri) {
        // 定义要查询的列
        String[] projection = {MediaStore.Images.Media.DATA};
        // 使用ContentResolver来查询内容提供者，获取包含指定列（文件路径）的Cursor
        Cursor cursor = getContentResolver().query(contentUri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String path = cursor.getString(column_index);
            cursor.close();
            return path;
        }
        return null;
    }

    /**
     * 获取文件MimeType类型
     * @param filePath
     * @return
     */
    private String getMimeType(String filePath) {
        String extension = MimeTypeMap.getFileExtensionFromUrl(filePath);
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }
}
